/**
 * clickEnbleDom:点赞对象
 * duration：循环时间
 */

type Options = {
    duration: number,
    onComplete: () => void
};

const dianZanHandler = (dianzanEnbleDom: HTMLElement,
    { duration = 50, onComplete = () => { } }: Partial<Options>) => {

    let id: NodeJS.Timer;

    const dianzan = (count: number) => {
        if (!dianzanEnbleDom) {
            throw new Error("没找到可点赞dom");
        }
        cancel();
        id = setInterval(() => {
            if (count <= 0) {
                console.log("点赞完毕");
                cancel();
                onComplete();
                return;
            }
            if (count % 100 == 0) {
                console.log(`还需要点赞 ${count}`)
            }
            dianzanEnbleDom.click(); count--;
        }, duration);
    }

    const cancel = () => clearInterval(id);

    return {
        dianzan,
        cancel
    }
}

export default (className: string) => {

    const dianZanCount = 1000;

    let isDianZan = false;

    const dianzanEnbleDom = document.getElementsByClassName(className)[0] as HTMLElement;

    const changeDianZan = () => {
        isDianZan = !isDianZan;
    };

    const { cancel, dianzan } = dianZanHandler(dianzanEnbleDom, {
        onComplete: changeDianZan,
    });

    console.log("点赞组件 isDianZan = ", isDianZan);

    const toggleDianZan = () => {
        console.log("点赞组件 isDianZan = ", isDianZan);
        changeDianZan();
        if (!!isDianZan) {
            dianzan(dianZanCount);
        } else {
            cancel();
        }
    };
    return {
        toggleDianZan
    }
}